package com.zxy.supplier_system.server.repository

import com.zxy.supplier_system.server.entity.Market
import com.zxy.supplier_system.server.entity.ProcurementReceipt
import com.zxy.supplier_system.server.entity.SystemService
import com.zxy.supplier_system.server.utils.SpecificationUtils
import com.zxy.supplier_system.server.utils.joinOnce
import org.springframework.data.jpa.domain.Specification
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
import java.time.LocalDate

interface ProcurementReceiptRepository : JpaRepository<ProcurementReceipt, Int>,
    JpaSpecificationExecutor<ProcurementReceipt> {

    fun findByIdAndProcurement_CreatedBy_SystemService(id: Int, procurement_systemService: SystemService): ProcurementReceipt?

    object Specifications {
        fun createdDateTimeGreaterThanOrEqualTo(startDate: LocalDate?): Specification<ProcurementReceipt> {
            return Specification { root, _, criteriaBuilder ->
                startDate?.let {
                    criteriaBuilder.greaterThanOrEqualTo(root.get("createdDateTime"), it)
                }
            }
        }

        fun createdDateTimeLessThanOrEqualTo(endDate: LocalDate?): Specification<ProcurementReceipt> {
            return Specification { root, _, criteriaBuilder ->
                endDate?.let {
                    criteriaBuilder.lessThanOrEqualTo(root.get("createdDateTime"), it)
                }
            }
        }

        fun validatedDateTimeGreaterThanOrEqualTo(startDate: LocalDate?): Specification<ProcurementReceipt> {
            return Specification { root, _, criteriaBuilder ->
                startDate?.let {
                    criteriaBuilder.greaterThanOrEqualTo(root.get("validatedDateTime"), it)
                }
            }
        }

        fun validatedDateTimeLessThanOrEqualTo(endDate: LocalDate?): Specification<ProcurementReceipt> {
            return Specification { root, _, criteriaBuilder ->
                endDate?.let {
                    criteriaBuilder.lessThanOrEqualTo(root.get("validatedDateTime"), it)
                }
            }
        }

        fun procurementSupplierIn(procurementIds: List<Int>): Specification<ProcurementReceipt> {
            return SpecificationUtils.`in`({ root ->
                root.joinOnce<ProcurementReceipt, Market>("procurement").get("id")
            }, procurementIds)
        }

    }


}
